package jupiter.node;

import java.util.ArrayList;
import java.util.HashMap;


import jupiter.message.Message;

import org.json.*;

public class Node {
	protected Address address;
	
	//only global node needs directed (by address) (I think), everything else should just send to everyone
	
	//we should make sure there can be no cycles ....
	private ArrayList<Node> fromNodes; //nodes I get messages from
	private ArrayList<Node> toNodes; //nodes I send messages to
	
	
	public Node( Address a) {
		address = a;
		//add to DomainNode
		GlobalNode.getDomain(a).addNode(this);
	}
	public String domain(){
		return "";
	}
	/*
	 * Listens to a location
	 */
	public void listenTo(Address a){
		//find node we want to listen to
		
		Node n = GlobalNode.getDomain(a).getNode(a);
		fromNodes.add(n);
		n._addListener(this);
		
	}
	/**
	 * Stops listening on a location
	 * @param a
	 */
	public void stopListening(Address a){
		Node n = GlobalNode.getDomain(a).getNode(a);
		fromNodes.remove(n);
		n._removeListener(this);
	}

	protected void _addListener(Node n){
		//add to toNodes, add yourself to n's fromNodes, 
		toNodes.add(n);
	}
	protected void _removeListener(Node n){
		toNodes.remove(n);
		//if no toNodes remove this guy
		if(toNodes.size() == 0)
			destroy();
	}
	
	public JSONObject sendMessage(Message m){
		for(Node n: fromNodes){
			n.sendMessage(m);
		}
		return null;
	}
	
	public void destroy(){
		//go through fromNodes and remove
		
		GlobalNode.getDomain(address).removeNode(this);
		//remove myself from each fromNode
		for(Node f : fromNodes){
			f._removeListener(this);
		}
		// remove each toNodes link back here
		for(Node t : toNodes){
			t.stopListening( this.address );
		}
	}
	
	
	
	
	public String node(){
		return address.node();
	}
	public String address(){
		return address.toString();
	}
}
